package test.android.lin.fragmenttest;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by linxiaobin on 2016/3/21.
 */
public class NewsTitleFragment extends Fragment implements AdapterView.OnItemClickListener {
    private ListView newTitleListView;
    private List<News> newsList;
    private NewsAdapter adapter;
    private boolean isTwoPane;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null)
            isTwoPane = true;
        else
            isTwoPane = false;
        Log.e("isTwoPane", String.valueOf(isTwoPane));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        newsList = getNews();
        adapter = new NewsAdapter(context,R.layout.news_item, newsList);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag, container, false);

        newTitleListView = (ListView)( view.findViewById(R.id.news_title_list_view));
        Log.e("r",(newTitleListView !=null)?"not null":"null");
        newTitleListView.setAdapter(adapter);
        newTitleListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        News news = newsList.get(position);
        if (isTwoPane) {
            NewsContentFragment fragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
            fragment.refresh(news.getTitle(), news.getContent());
        } else {
            NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent());
        }
    }

    public List<News> getNews() {
        List<News> newsList = new ArrayList<>();
        News news1 = new News();
        news1.setTitle("linxiaobinfgdgfdgfadf fdffd d sdsaf dgd");
        news1.setContent("zhejiangdaxue dfgdfadsdsfsddsglkdjgdljgkd");
        newsList.add(news1);
        News news = new News();
        news.setTitle("linxiaobfadsfsadfin2");
        news.setContent("zfdfdfdfadsssssssssssserereregg");
        newsList.add(news);
        return newsList;
    }

}
